package purchaseStore

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"insighttracking/apps/purchase/auth"
	"insighttracking/apps/purchase/internal/svc"
	"insighttracking/apps/purchase/internal/types"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type AddPurchaseStoreApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewAddPurchaseStoreApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *AddPurchaseStoreApiLogic {
	hostname, _ := os.Hostname()
	return &AddPurchaseStoreApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *AddPurchaseStoreApiLogic) AddPurchaseStoreApi(req *types.AddPurchaseStoreReq) (resp string, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	fmt.Println(k.MapToString(accountInfo), "用户信息")
	// 1.根据采购计划订单查询当前采购订单信息
	purchaseStoreEntity, err := service.PurchaseStoreService.GetPurchaseStoreByIdApi(l.ctx, accountInfo.EnterpriseId, req.PurchaseStoreID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return "", errors.New("传递的采购入库单id错误")
	}
	spuEntity, err := service.SpuService.GetSpuDetailByIdListApi(l.ctx, []int64{req.SpuID})
	if err != nil || len(spuEntity) == 0 {
		return "", errors.New("传递的商品id错误")
	}
	storeCount, _ := decimal.NewFromString(req.StoreCount)
	purchaseStoreDetailEntities, err := service.PurchaseStoreDetailService.GetPurchaseStoreByPurchaseStoreIdSpuIdApi(l.ctx, req.PurchaseStoreID, req.SpuID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return "", errors.New("传递的采购入库单id或商品id错误")
	}
	inCount := purchaseStoreDetailEntities.StoreCount.Add(storeCount)
	var storeAmount decimal.Decimal
	if inCount.Compare(purchaseStoreDetailEntities.PurchaserCount) >= 0 {
		storeAmount = purchaseStoreDetailEntities.PurchaserAmount
	} else {
		storeAmount = inCount.Mul(purchaseStoreDetailEntities.PurchaserPrice)
	}
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	if err = service.PurchaseStoreDetailService.AddPurchaseStoreDetailByIdApi(
		l.ctx,
		tx,
		purchaseStoreDetailEntities.ID,
		inCount,
		storeAmount,
		enum.PurchaseStoreEnum); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("操作失败")
	}
	// 修改主表的入库总重量
	if err = service.PurchaseStoreService.ModifyTotalCountByIdApi(l.ctx, tx, req.PurchaseStoreID, storeCount.Add(purchaseStoreEntity.TotalCount), accountInfo.PersonId); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("操作失败")
	}
	// 库存增加
	if err = service.SpuInventoryService.IncrInventoryApi(l.ctx, tx, accountInfo.EnterpriseId, purchaseStoreEntity.WarehouseID, req.SpuID, storeCount); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("操作失败")
	}
	// 货位库存增加
	if _, err = service.SpuShelfGridInventoryService.IncrGridInventoryApi(l.ctx, tx, accountInfo.EnterpriseId, purchaseStoreDetailEntities.ShelfID, purchaseStoreDetailEntities.SpuID, purchaseStoreEntity.SupplierID, "", purchaseStoreDetailEntities.BatchNumber, storeCount); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("操作失败")
	}

	// 库存记录
	if err = service.InventRecordService.CreateInventRecordApi(l.ctx, tx, &model.InventoryRecordEntity{
		EnterpriseID: accountInfo.EnterpriseId,                   // 关联到enterprise表主键id
		SpuID:        req.SpuID,                                  // 商品主键,关联到spu表主键id
		Types:        0,                                          // 类型,0表示入库,1表示出库
		Source:       0,                                          // 来源,0表示正常出入口,10表示盘点报损报溢,20表调拨
		WarehouseID:  purchaseStoreEntity.WarehouseID,            // 仓库id,关联到warehouse表主键id
		ChangeCount:  storeCount,                                 // 变动数量
		Price:        spuEntity[0].PurchasePrice,                 // 单价
		Amount:       storeCount.Mul(spuEntity[0].PurchasePrice), // 金额
		ShelfID:      purchaseStoreDetailEntities.ShelfID,        // 货位ID
		BatchNumber:  purchaseStoreDetailEntities.BatchNumber,    // 批次号
	}); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("操作失败")
	}
	// 修改称重的状态
	if err = service.SpuStoreWeighRecordService.ModifyStatusBySpuIdApi(l.ctx, tx, accountInfo.EnterpriseId, req.SpuID); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("操作失败")
	}
	if err = tx.Commit(); err != nil {
		return "", err
	}
	// 后面进行的数据操作
	go ModifyStatus(accountInfo.EnterpriseId, purchaseStoreEntity.PurchaseOrdersID, purchaseStoreEntity.ID)
	return "操作成功", nil
}
